package hephaestus.server.proxy;

import java.net.*;
import java.io.*;

public class ProxyServer {
	private ConnectionManager connections;
	private IncomingManager incoming;
	private int port;
	
	private final static int INCOMING_QUEUE_CAPACITY = 20; 
	private final static int ACCEPT_TIMEOUT = 10000; // milliseconds
	
	public ProxyServer(String internalAddressPrefix, int port)
	{
		connections = new ConnectionManager();
		incoming = new IncomingManager(connections, internalAddressPrefix, INCOMING_QUEUE_CAPACITY);
		this.port = port;
	}
	
	public void host()
	{
		boolean accepting = false;
		ServerSocket server = null;
		System.out.println("Initialising server socket...");
		try
		{
			server = new ServerSocket();
			server.bind(new InetSocketAddress("", port));
			server.setSoTimeout(ACCEPT_TIMEOUT);
			accepting = true;
			System.out.println("Running accept loop.");
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		while(accepting)
		{
			try
			{
				Socket client = server.accept();
				incoming.incomingConnection(client);
			}
			catch(SocketTimeoutException timeout)
			{
			}
			catch(Exception e)
			{
				e.printStackTrace();
				accepting = false;
			}
		}
	}
	
	public static void main(String[] args)
	{
		System.out.print("Starting proxy server...");
		ProxyServer server = new ProxyServer("127.0.0.1", 28000);
		System.out.println("done!");
		server.host();
		System.out.println("Proxy server closing!");
	}
}
